package com.xiyu.service.repository.customer.follow;

import com.xiyu.service.model.customer.follow.CustomerFollow;
import com.xiyu.service.model.customer.follow.CustomerFollowTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.sql.ast.Expression;
import org.babyfish.jimmer.sql.ast.tuple.Tuple3;

import java.util.List;
import java.time.LocalDateTime;

public interface CustomerFollowRepository extends JRepository<CustomerFollow, Long> {
    CustomerFollowTable customerFollowTable = CustomerFollowTable.$;

    default List<Tuple3<Long, LocalDateTime, Long>> keyTrendQuery(List<Long> userOwnerIds, List<Long> ownerIds, LocalDateTime[] times){
        return sql().createQuery(customerFollowTable)
                .where(customerFollowTable.ownerId().in(userOwnerIds))
                .whereIf(!ownerIds.isEmpty(), customerFollowTable.ownerId().in(ownerIds))
                .where(customerFollowTable.createTime().between(times[0], times[1]))
                .where(customerFollowTable.customer().isRecycle().eq(false))
                .groupBy(customerFollowTable.ownerId(), Expression.any().sql(LocalDateTime.class, "DATE_FORMAT(%e, '%Y-%m-%d')", customerFollowTable.followTime()))
                .select(customerFollowTable.ownerId(), Expression.any().sql(LocalDateTime.class, "DATE_FORMAT(%e, '%Y-%m-%d')", customerFollowTable.followTime()),
                        Expression.any().sql(Long.class, "COUNT(DISTINCT %e)", customerFollowTable.customerId()))
                .execute();
    }


}